<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="role-span">项目招标一览表</span>
        <router-link
          v-if="projectProfile.id"
          :to="{ path: '/project/process', query: { pid: projectProfile.id } }"
          class="edit-link"
        >
          返回项目详情
        </router-link>
      </div>
      <table class="cus-table">
        <tr>
          <td>项目名称</td>
          <td>{{ projectProfile.name }}</td>
          <td>项目编号</td>
          <td>{{ projectProfile.code }}</td>
        </tr>
        <tr>
          <td>付款条件</td>
          <td>{{ projectProfile.paymentClause }}</td>
          <td>合同对接人及联系方式</td>
          <td>{{ projectProfile.contact }}</td>
        </tr>
      </table>

      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span class="role-span">供应商总价一览表</span>
        </div>
        <el-table :data="supplierList">
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="code" label="供应商代码" width="130"></el-table-column>
          <el-table-column prop="name" label="供应商名称"></el-table-column>
          <el-table-column prop="contactPerson" label="联系人姓名"></el-table-column>
          <el-table-column prop="contactPhone" label="联系人电话"></el-table-column>
          <el-table-column prop="detail.email" label="联系邮箱"></el-table-column>
          <el-table-column prop="bidStatus" label="供应商项目状态">
            <template slot-scope="scope">
              <span :class="{ error: scope.row.bidStatus === 'REJECT' }">
                {{ dict.label.project_supplier_status[scope.row.bidStatus] }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="offerTime" label="报价时间" width="150"></el-table-column>
          <el-table-column prop="combinedPrice" label="含税总报价" sortable></el-table-column>
          <el-table-column></el-table-column>
        </el-table>
      </el-card>

      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span class="role-span">采购报价总览</span>

          <div class="box-card-btn">
            <el-button :type="unExpanded ? 'primary' : 'warning'" @click="expandedAllOffer">
              {{ unExpanded ? '展开' : '收起' }}所有报价信息
            </el-button>

            <el-button
              type="primary"
              :disabled="awardNotEqualPlanLength"
              @click="awardGo"
              v-if="projectProfile.status == 'OPEN'"
            >
              授标
            </el-button>

            <el-button type="danger" v-if="projectProfile.status !== 'AWARD'" @click="makeTwice">
              澄清
            </el-button>
          </div>
        </div>
        <el-table
          :data="projectProfile.projectPlans"
          :expand-row-keys="expandRows"
          row-key="id"
          class="project-plan-table"
        >
          <el-table-column type="index"></el-table-column>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-card shadow="never">
                <el-table :data="supplierPlansGather[scope.row.id]" stripe>
                  <el-table-column prop="supplierName" label="供应商名称"></el-table-column>
                  <el-table-column prop="detail.model" label="型号">
                    <template slot-scope="scope">
                      <span
                        :class="{
                          'offer-red':
                            supplierPlansGather[scope.row.planId][0].detail.model !=
                            scope.row.detail.model,
                        }"
                      >
                        {{ scope.row.detail.model }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="detail.configuration" label="配置">
                    <template slot-scope="scope">
                      <span
                        :class="{
                          'offer-red':
                            supplierPlansGather[scope.row.planId][0].detail.configuration !=
                            scope.row.detail.configuration,
                        }"
                      >
                        {{ scope.row.detail.configuration }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="detail.deliveryDate" label="交货日期" width="150">
                    <template slot-scope="scope">
                      <span
                        :class="{
                          'offer-red':
                            supplierPlansGather[scope.row.planId][0].detail.deliveryDate !=
                            scope.row.detail.deliveryDate,
                        }"
                      >
                        {{ scope.row.detail.deliveryDate | moment('YYYY-MM-DD') }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="detail.tax" label="税率">
                    <template slot-scope="scope">
                      <span
                        :class="{
                          'offer-red':
                            supplierPlansGather[scope.row.planId][0].detail.tax !=
                            scope.row.detail.tax,
                        }"
                      >
                        {{ scope.row.detail.tax }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="offerAmount" label="数量" width="80"></el-table-column>
                  <el-table-column prop="unitPriceWithoutTax" label="未税单价(元)">
                    <template slot-scope="scope">
                      <span>
                        {{ currency(scope.row.unitPriceWithoutTax) }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="unitPriceWithTax" label="含税单价(元)">
                    <template slot-scope="scope">
                      <span>
                        {{ currency(scope.row.unitPriceWithTax) }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="combinedPrice" label="含税合价(元)" width="120">
                    <template slot-scope="scope">
                      <span>
                        {{ currency(scope.row.combinedPrice) }}
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" align="center" label="选择授标">
                    <template slot-scope="scope">
                      <div>
                        <el-radio
                          v-if="scope.$index != 0"
                          v-model="awardMap[scope.row.planId]"
                          :label="scope.row.supplierId"
                          @change="awardChanged(scope)"
                          :disabled="projectAwarded"
                        ></el-radio>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </template>
          </el-table-column>
          <el-table-column prop="code" label="物料编号" width="130"></el-table-column>
          <el-table-column prop="name" label="物料名称"></el-table-column>
          <el-table-column prop="detail.configuration" label="配置"></el-table-column>
          <el-table-column label="交货日期">
            <template slot-scope="scope">
              <div>{{ scope.row.detail.deliveryDate | moment('YYYY-MM-DD') }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="detail.amount" label="物料数量"></el-table-column>
          <el-table-column prop="supplierName" label="授标对象">
            <template slot-scope="scope">
              <div class="supplier-name">
                {{ scope.row.supplierName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="combinedPrice" label="含税价格(元)"></el-table-column>
        </el-table>
      </el-card>
    </el-card>

    <el-dialog title="澄清" :visible.sync="showTwiceDialog" width="50%" :before-close="closeDialog">
      <el-form :rules="twiceRules" :model="twiceInfo" ref="twiceInfoForm" label-width="120px">
        <el-form-item prop="reason" label="理由">
          <el-input
            type="textarea"
            maxlength="100"
            show-word-limit
            resize="none"
            v-model="twiceInfo.reason"
            autocomplete="off"
            rows="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="供应商选择">
          <el-checkbox
            v-model="twiceInfo.supplierIds"
            :label="supplier.id"
            v-for="(supplier, index) in supplierList"
            :key="index"
          >
            {{ supplier.name }}
          </el-checkbox>
        </el-form-item>
        <el-form-item prop="twiceOpenTime" label="澄清延迟时间">
          <el-date-picker
            v-model="twiceInfo.twiceOpenTime"
            type="datetime"
            value-format="timestamp"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTwiceDialog = false">取 消</el-button>
        <el-button type="primary" @click="twiceGo" :loading="twiceLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as ProjectRequest from '@/api/project';
  import { resultFormatter } from '@/utils';
  import { accAdd, currency } from '@/utils/math';
  import FormRuleConf from '@/FormRuleConf';

  const TWICE_TMP = {
    reason: '',
    supplierIds: [],
    twiceOpenTime: 0,
  };

  export default {
    name: 'OpenTable',
    dicts: ['project_supplier_status'],
    data() {
      return {
        ...FormRuleConf.Project,
        pid: null,
        projectProfile: {},
        supplierList: [],
        supplierPlansGather: {},
        expandRows: [],
        awardMap: {},

        twiceInfo: {},
        showTwiceDialog: false,
        twiceLoading: false,
      };
    },
    watch: {
      $route() {
        this.init();
      },
    },
    computed: {
      unExpanded() {
        return this.expandRows.length === 0;
      },
      projectAwarded() {
        return this.projectProfile.status === 'AWARD';
      },
      awardNotEqualPlanLength() {
        if (!this.projectProfile.projectPlans) {
          return false;
        }
        return this.projectProfile.projectPlans.length != Object.keys(this.awardMap).length;
      },
    },
    mounted() {
      this.init();
    },
    methods: {
      /**
       * 初始化
       */
      init() {
        const { pid } = this.$route.query;
        this.pid = pid;
        if (!this.pid) {
          this.$EventBus.$emit('closeCurrentPage');
          this.$message.error('开标信息不出在,或者没有权限');
          return;
        }

        this.getProjectProfile();
      },
      /**
       * 获取项目信息
       */
      getProjectProfile() {
        ProjectRequest.getProfile({
          id: this.pid,
        }).then((res) => {
          // 还是先判断一下这个项目的阶段

          if (res.status !== 'OPEN' && res.status !== 'AWARD') {
            this.$EventBus.$emit('closeCurrentPage');
            this.$message.error('项目尚未开标');
            return;
          }

          this.projectProfile = {
            ...res,
            projectPlans: resultFormatter(res.projectPlans),
          };

          // 放置第一个
          this.projectProfile.projectPlans.forEach((plan) => {
            this.supplierPlansGather[plan.id] = [];
            const { model, configuration, deliveryDate, tax, amount } = plan.detail;
            this.supplierPlansGather[plan.id].push({
              supplierName: '',
              detail: {
                model,
                configuration,
                deliveryDate,
                tax,
              },
              // 为了兼容数据
              planId: plan.id,
              offerAmount: amount,
              unitPriceWithoutTax: '',
              unitPriceWithTax: '',
              combinedPrice: '',
            });
          });

          // 默认展开
          this.expandedAllOffer();
          // 获取供应商
          this.getSupplier();
        });
      },
      /**
       * 获取供应商
       */
      getSupplier() {
        ProjectRequest.getSupplier({
          projectId: this.pid,
        }).then((res) => {
          this.supplierList = resultFormatter(res.content).map((supplier) => {
            const { supplierPlans, bidStatus } = supplier;

            let combinedPrice = 0;
            let offerTime = null;

            supplierPlans.forEach((_) => {
              // 转化detail
              const plan = resultFormatter(_);
              // 报价时间
              if (!offerTime) {
                offerTime = this.$moment(plan.createTime).format('YYYY-MM-DD HH:mm:ss');
              }
              // 报价总计
              combinedPrice = accAdd(combinedPrice, plan.combinedPrice);

              if (bidStatus === 'REJECT') return;

              // 创建一个planId的集合
              if (!this.supplierPlansGather[plan.planId]) {
                this.supplierPlansGather[plan.planId] = [];
              }

              // 堆数据
              this.supplierPlansGather[plan.planId].push({
                ...plan,
                supplierId: supplier.id,
                supplierName: supplier.name,
              });
            });

            return {
              ...supplier,
              offerTime,
              combinedPrice: currency(combinedPrice),
            };
          });

          // 如果已经授标,则显示结果
          if (this.projectAwarded) {
            this.projectProfile.awardPlans.forEach((award) => {
              this.awardMap[award.planId] = award.supplierId;

              // 塞入供应商的名字
              for (const key in this.projectProfile.projectPlans) {
                if (this.projectProfile.projectPlans[key].id == award.planId) {
                  this.$set(
                    this.projectProfile.projectPlans[key],
                    'supplierName',
                    this.findSupplierById(award.supplierId).name,
                  );
                  break;
                }
              }
            });
            this.awardMap = { ...this.awardMap };
          }
        });
      },
      /**
       * 展开按钮
       */
      expandedAllOffer() {
        if (this.expandRows.length > 0) {
          this.expandRows = [];
        } else {
          this.expandRows = this.projectProfile.projectPlans.map((plan) => plan.id);
        }
      },
      /**
       * 授标选择
       */
      awardChanged(scope) {
        const { planId, supplierId, supplierName } = scope.row;

        for (const key in this.projectProfile.projectPlans) {
          if (this.projectProfile.projectPlans[key].id === planId) {
            this.$set(this.projectProfile.projectPlans[key], 'supplierName', supplierName);
            this.$set(this.projectProfile.projectPlans[key], 'combinedPrice', combinedPrice);
            break;
          }
        }
      },
      /**
       * 点击授标
       */
      awardGo() {
        const displayInfo = [];
        /**
         * 获取计划和供应商名称
         */
        this.projectProfile.projectPlans.forEach((plan, index) => {
          const { name, supplierName } = plan;
          displayInfo.push(`<p> ${index + 1}.  <b>${name}</b> 标的授予 <b>${supplierName}</b></p>`);
        });

        this.$confirm(
          `确定授标: ${displayInfo.join(
            '',
          )} <p style="color: red; font-size: 12px">确定授标之后, 无法修改授标对象. 请谨慎选择!!</p>`,
          '授标',
          {
            dangerouslyUseHTMLString: true,
          },
        )
          .then(() => {
            return ProjectRequest.setProjectAward({
              plans: Object.keys(this.awardMap).map((planId) => {
                return {
                  planId,
                  supplierId: this.awardMap[planId],
                };
              }),
              projectId: this.projectProfile.id,
            });
          })
          .then(() => {
            this.$message.success('授标完成!');
            this.getProjectProfile();
          });
      },
      /**
       * 通过Id寻找供应商
       */
      findSupplierById(id) {
        let result = {};

        if (!id || !this.supplierList) {
          return result;
        }

        for (const key in this.supplierList) {
          if (this.supplierList[key].id == id) {
            result = this.supplierList[key];
            break;
          }
        }
        return result;
      },

      /**
       *
       */
      makeTwice() {
        this.showTwiceDialog = true;
        // 初始化澄清对象
        TWICE_TMP.twiceOpenTime = this.projectProfile.openTime;
        this.twiceInfo = { ...TWICE_TMP };
      },
      closeDialog() {
        // 初始化澄清对象
        this.showTwiceDialog = false;
        TWICE_TMP.twiceOpenTime = this.projectProfile.openTime;
        this.twiceInfo = { ...TWICE_TMP };
      },
      twiceGo() {
        if (this.twiceLoading) {
          return;
        }

        this.$refs['twiceInfoForm'].validate((valid) => {
          if (valid) {
            this.twiceLoading = true;
            ProjectRequest.setOfferAgent({
              projectId: this.projectProfile.id,
              ...this.twiceInfo,
            })
              .then((res) => {
                this.$message.success('澄清已发出');
                this.closeDialog();
                this.$EventBus.$emit('closeCurrentPage');
              })
              .finally(() => {
                this.twiceLoading = false;
              });
          }
        });
      },
      currency,
    },
  };
</script>

<style lang="scss" scoped>
  .edit-link {
    color: #2222ff;
    font-size: 12px;
    margin-left: 5px;
  }

  .cus-table {
    font-size: 14px;
    margin-bottom: 10px;

    td:nth-child(odd) {
      width: 160px;
    }
  }

  .project-plan-table {
    /deep/ .el-table__expanded-cell {
      padding: 10px;
      background-color: #eeeeee;
    }

    /deep/ .el-radio__label {
      display: none;
    }
  }

  .offer-red {
    color: #ee2200;
  }

  .supplier-name {
    color: #00cc22;
    font-weight: bolder;
  }
</style>
